package hu.plusone.eregister.service.impl;

import hu.plusone.eregister.entity.Diary;
import hu.plusone.eregister.entity.Lesson;
import hu.plusone.eregister.repository.DiaryRepository;
import hu.plusone.eregister.repository.LessonRepository;
import hu.plusone.eregister.service.AppService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

@Service
public class ServiceImpl implements AppService {

    private final DiaryRepository diaryRepository;
    private final LessonRepository lessonRepository;

    @Autowired
    public ServiceImpl(DiaryRepository diaryRepository, LessonRepository lessonRepository) {
        this.diaryRepository = diaryRepository;
        this.lessonRepository = lessonRepository;
    }

    @Override
    public List<Diary> getDiaries(int pageSize, int page) {
        Pageable pageable = new PageRequest(page, pageSize, sortDiariesByLastEdited());
        return diaryRepository.findAll(pageable).getContent();
    }

    @Override
    public List<Lesson> getLessons(String diaryId, int pageSize, int page) {
        Assert.notNull(diaryId);
        Pageable pageable = new PageRequest(page, pageSize, sortLessonsByDate());
        return lessonRepository.findAll(pageable).getContent();
    }

    @Override
    public void saveLesson(Lesson lesson) {
        Assert.notNull(lesson);
        lessonRepository.save(lesson);
    }

    @Override
    public void deleteLesson(Lesson lesson) {
        Assert.notNull(lesson);
        lessonRepository.delete(lesson);
    }

    @Override
    public long countDiaries() {
        return diaryRepository.count();
    }

    private Sort sortLessonsByDate() {
        return new Sort(Sort.Direction.DESC, "date");
    }

    private Sort sortDiariesByLastEdited() {
        return new Sort(Sort.Direction.DESC, "lastEdited");
    }
}
